# _*_ coding:utf-8 _*_
import pygame
from pygame.locals import *
import time
import random

ENEMY_EVENT=pygame.USEREVENT #创建事件发生的常量

ENEMY_FIRE_EVENT=pygame.USEREVENT+1 #创建事件发生的常量
print("ENEMY_FIRE_EVENT is:",ENEMY_FIRE_EVENT)


class Entity(pygame.sprite.Sprite):
    '''画布基础实体类'''
    def __init__(self,screen_temp,x,y,image):
        self.screen = screen_temp
        self.x = x
        self.y = y
        self.image=pygame.image.load(image)

    def display(self):
        '''把实体绘制进窗口中'''
        self.screen.blit(self.image,(self.x,self.y))

    def move_left(self,step,boundary_value):
        '''左移动，并判断防止越界'''
        self.x-=step
        if self.x<boundary_value:
            self.x=boundary_value

    def move_right(self,step,boundary_value):
        '''右移动，并判断防止越界'''
        self.x+=step
        if self.x>boundary_value:
            self.x=boundary_value

    def move(self,step):
        self.y+=step


class EnemyPlane(Entity):
    '''敌机'''

    def __init__(self,screen_temp):
        self.x=random.choice(range(408))
        self.y=-75
        self.screen=screen_temp
        self.image=pygame.image.load("./images/e2.png")
        self.bullet_list=[]


    def display(self):
        '''绘制敌机到窗口中，并发射子弹'''
        for bullet in self.bullet_list:
            bullet.display()
            # 移动子弹，并判断是否越界
            if bullet.move_down():
                self.bullet_list.remove(bullet)
            # 英雄子弹与敌机子弹的碰撞检测
        self.screen.blit(self.image, (self.x, self.y))

    def move(self,step,hero):
        self.y+=step
        #遍历玩家子弹，并做碰撞检测
        for bo in hero.bullet_list:
            if bo.x>self.x+12 and bo.x<self.x+92 and bo.y>self.y+20 and bo.y<self.y+60:
                hero.bullet_list.remove(bo)
                return True

    def fire(self):
        '''敌机子弹'''
        for i in range(50):
            self.bullet_list.append(Bullet(self.screen, self.x, self.y, "./images/pd.png"))


    def bullet_collide(self,hero):
          for bullet in self.bullet_list:
             for b in hero.bullet_list:
                if abs(bullet.x-b.x)<=5 and abs(b.y-bullet.y)<=3:
                    hero.bullet_list.remove(b)
                    self.bullet_list.remove(bullet)
                    print("子弹碰撞")
                    continue
             if bullet.x>hero.x+12 and bullet.x<hero.x+92 and bullet.y>hero.y+20 and bullet.y<hero.y+60:
                 print("敌机子弹射中英雄飞机")
                 return True


class Bullet(Entity):
    def __init__(self,screen_temp,x,y,image):
        self.x=x+51
        self.y=y
        self.screen=screen_temp
        self.image=pygame.image.load(image)

    def move_top(self):
        self.y-=10
        if self.y<-20:
            return True

    def move_down(self):
        self.y += 10
        if self.y > 512:
            return True

class HeroPlane(Entity):
    '''玩家飞机类'''

    def __init__(self,screen_temp,x,y,image):

        self.x=x
        self.y=y
        self.screen=screen_temp
        self.image=pygame.image.load(image)
        self.bullet_list=[] #存储发射出去的子弹
        self.hero_kill = False  # 英雄飞机是否被打下来

    def display(self):
        '''绘制玩家飞机到窗口中'''
        for bullet in self.bullet_list:
            bullet.display()
            #移动子弹，并判断是否越界
            if bullet.move_top():
                self.bullet_list.remove(bullet)
        self.screen.blit(self.image,(self.x,self.y))

    def fire(self):
         self.bullet_list.append(Bullet(self.screen,self.x,self.y,"./images/pd.png"))



def key_control(hero_temp):
    '''键盘控制函数'''

    #获取事件
    for event in pygame.event.get():
        #判断是否是点击了退出按钮
        if event.type ==QUIT:
            print("exit")
            exit()

    #获取按下的健（返回的是元祖值）
    pressed_keys=pygame.key.get_pressed()
    # print("")
    # print(pressed_keys)
    # print("")
    #检查是不是按下了d键或者left键
    if pressed_keys[K_LEFT] or pressed_keys[K_a]:
        print("left")
        hero_temp.move_left(5,0)

    elif pressed_keys[K_RIGHT] or pressed_keys[K_d]:
        print("right")
        hero_temp.move_right(5,406)

    if pressed_keys[K_SPACE]:
        print("space")
        hero_temp.fire()

#创建游戏主页窗口，并添加滚动背景

def main():
    '''游戏主函数'''

    #1:创建窗口
    screen=pygame.display.set_mode((512,568),0,0)

    #2：创建一个游戏背景图片(512*1536)
    background=pygame.image.load("./images/bg2.jpg")
    #print("the image exists:",os.path.exists("./images/bg2.jpg"))
    # 初始化游戏背景图片标轴y的值
    m=-968

    #创建玩家飞机对象
    hero=HeroPlane(screen,200,450,"./images/me.png")
    # pygame.time.set_timer(ENEMY_FIRE_EVENT, 1000)
    # pygame.time.set_timer(ENEMY_EVENT, 500)

    enemylist=[]
    while True:

        screen.blit(background, (0, m))
        if not hero.hero_kill:

            # 绘制位图

            m += 2
            if m >= -200:
                m = -968

            hero.display()
            key_control(hero)
            #随机输出敌机
            if random.choice(range(50))==10:
                enemyplane=EnemyPlane(screen)
                enemylist.append(enemyplane)

            # 遍历所有敌机，显示敌机，移动敌机，并与玩家检测子弹碰撞
            for en in enemylist:
                print("enemy plane")
                en.display()
                if en.move(4, hero):
                    enemylist.remove(en)
                if random.choice(range(20))==5:
                    en.fire()
                if en.bullet_collide(hero):
                    enemylist.remove(en)
                    hero.hero_kill=True
                    break
        else :
            print("游戏结束")
            boom_image = pygame.image.load("./images/bomb3.png")
            print("sss")

            screen.blit(boom_image, (hero.x,hero.y))
            pygame.display.update()
            break



        # 更新屏幕显示
        pygame.display.update()
        # 定时睡眠
        time.sleep(0.04)






if __name__=="__main__":
    main()



